module.exports = class extends require('egg').Service {
  async select({ city, page, audit_status = 0 }) {
    const { ctx } = this;
    let where = [];
    if (audit_status) where.push(`audit_status = ${audit_status}`);
    if (city) where.push(`city in ('${city}', '', null)`);
    if (where.length) where = `where ${where.join(' and ')}`;
    else where = '';

    const list = await ctx.helper.query({
      query: `select * from "meet_${await ctx.service.config.getVal('post_db')}" 
        ${where} order by id DESC limit 10 offset ${(page - 1) * 10}`,
      json: ['imgs']
    });

    return list;
  }
  async find(id) {
    const { ctx } = this;
    const res = await ctx.helper.query({
      query: `select * from "meet_${await ctx.service.config.getVal('post_db')}" where id = ${id}`,
      json: ['imgs'],
      find: true
    });

    // 增加PV
    await ctx.helper.query({ query: `update "meet_${await ctx.service.config.getVal('post_db')}" set pv_total = pv_total + 1 where id = ${id}` });
    return res;
  }
  /** 解锁一个帖子 */
  async unlock({ uid, post_id }) {
    const { ctx } = this;

    const post = await ctx.helper.query({
      query: `select * from "meet_${await ctx.service.config.getVal('post_db')}" where id = ${post_id}`,
      find: true
    });

    const user = await ctx.helper.query({ query: `select * from "meet_user" where id = ${uid}`, find: true });
    if (user.coin < post.unlock_cost) {
      // 金币不足，需要补充
      return false;
    } else {
      await ctx.helper.trans(async () => {
        // 解锁人扣除金币
        await ctx.helper.query({ query: `update "meet_user" set coin = coin - ${post.unlock_cost} where id = ${uid}` });
        // 发帖人增加一半的解锁金币
        await ctx.helper.query({ query: `update "meet_user" set coin = coin + ${Math.floor(post.unlock_cost / 2)} where id = ${post.post_uid}` });
      });

      return true;
    }
  }
  /** 新建帖子 */
  async new(data) {
    const { ctx } = this;

    return await ctx.helper.query({
      query: `insert into "meet_${await ctx.service.config.getVal('post_db')}" 
      (post_uid, text, contact, create_time, imgs, city, unlock_cost) 
      values (
        ${data.uid}, '${data.text || ''}', '${data.contact}', '${ctx.helper.formatTime()}', 
        '${data.imgs ? JSON.stringify(data.imgs.split(',')) : ''}', '${data.city}', ${Math.abs(data.unlock_cost || 0)}
      )`
    });
  }
};
